package blogger.servlets;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import blogger.model.entity.UserEntity;
import blogger.model.utils.EMF;



public class RegServlet extends HttpServlet{
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
            IOException {
        String login = httpServletRequest.getParameter("login");
        String pass = httpServletRequest.getParameter("pass");
        String mail = httpServletRequest.getParameter("mail");
        EntityManager em = EMF.get().createEntityManager();
        Query query1 = em
                .createQuery("select u from UserEntity u where u.login = :login");
        query1.setParameter("login", login);
        Query query2 = em
                .createQuery("select u from UserEntity u where u.mail = :mail");
        query2.setParameter("mail", mail);
        UserEntity user = null;
        try {
            user = (UserEntity) query1.getSingleResult();
            httpServletRequest.setAttribute("error", true);
            httpServletRequest.getRequestDispatcher("registration.jsp")
                    .forward(httpServletRequest, httpServletResponse);
        } catch (NoResultException nre1) {
            try {
                user = (UserEntity) query2.getSingleResult();
                httpServletRequest.setAttribute("error", true);
                httpServletRequest.getRequestDispatcher("registration.jsp")
                        .forward(httpServletRequest, httpServletResponse);
            } catch (NoResultException nre2) {
                try {
                    user = new UserEntity(login, pass, mail);
                    em.persist(user);
                } finally {
                    em.close();
                }
            }
        }
        httpServletRequest.setAttribute("login", login);
        httpServletRequest.setAttribute("pass", pass);
        httpServletRequest.getRequestDispatcher("regend.jsp").forward(httpServletRequest, httpServletResponse);
    }

}
